package com.uifuture;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author:LiangTao
 * @Description:
 * @Date: Created in 17:56 2018/5/27.
 */
public class GzipUtils {

    //压缩
    public static byte[] gzip(byte[] data) throws Exception{
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream=new GZIPOutputStream(byteArrayOutputStream);
        //目前理解的压缩主要逻辑应该在这里面？？？
        gzipOutputStream.write(data);
        gzipOutputStream.flush();
        gzipOutputStream.close();
        gzipOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }
    //解压
    public static byte[] ungzip(byte[] data) throws Exception{
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(data);
        GZIPInputStream gzipInputStream=new GZIPInputStream(byteArrayInputStream);
        byte[] tempByte=new byte[1024];
        int num=-1;
        //目前理解的解压主要逻辑应该在这里面？？？
        while((num = gzipInputStream.read(tempByte))!=-1){
            byteArrayOutputStream.write(tempByte,0,num);
        }
        byteArrayOutputStream.flush();
        byteArrayOutputStream.close();
        byteArrayInputStream.close();
        gzipInputStream.close();
        return byteArrayOutputStream.toByteArray();
    }
}
